import platform
 
operating_system = platform.system()
 
import time
import sys
exec_path = ""
if len(sys.argv) > 1:
    sys.path.append(sys.argv[1])
    exec_path = sys.argv[1]
sys.path.append("/Users/guilongcheng/bin/")

import selenium
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import timedelta
 
def time_to_seconds(time_str):
    parts = time_str.split(':')
    if len(parts) == 3:
        hours = int(parts[0])
        minutes = int(parts[1])
        seconds = hours * 3600 + minutes * 60 + int(parts[2])
    if len(parts) == 2:
        minutes = int(parts[0])
        seconds = minutes * 60 + int(parts[1])
    return seconds

if operating_system == "Windows":
    print("当前操作系统是Windows")
    execfile = "msedgedriver.exe"
elif operating_system == "Darwin":
    print("当前操作系统是Mac")
    execfile = "msedgedriver"
else:
    print("未知操作系统")
print(exec_path + execfile)
#browser = webdriver.Edge(executable_path=exec_path+execfile,capabilities={"page_load_strategy":"normal"})
try:
    browser = webdriver.Edge(executable_path=exec_path + execfile, capabilities={"page_load_strategy": "normal"})
except:
    print(f"尝试采用server加载！")
    from selenium.webdriver.edge.service import Service
    service = Service(executable_path=exec_path+execfile)
    browser = webdriver.Edge(service=service)
browser.maximize_window()
browser.implicitly_wait(30)

username=""
userkey=""
browser.get("https://www.ejxjy.com/login.html")
if browser.find_element(By.XPATH,'//*[@id="username"]'):         #用户名
    browser.find_element(By.XPATH,'//*[@id="username"]').send_keys(username)
if browser.find_element(By.XPATH,'//*[@id="password"]'):         # 密码
    browser.find_element(By.XPATH,'//*[@id="password"]').send_keys(userkey)

## 点击登录
elem=WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="loginForm"]/ul/li[4]')))
elem.click()
print(browser.window_handles,browser.current_window_handle)
print("登录")
## 判断登录是否正常并点击确定
try:
    elem=WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="loaded"]/input')))
    elem.click()
    print("登录正常，并点击确定!")
    print(browser.window_handles,browser.current_window_handle)
except:
    print("登录失败！请检查用户名和密码！")
    exit()

## 点击公需科目
browser.switch_to.window(browser.window_handles[0])
elem=WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="one1"]')))
elem.click()
print("公需科目")
## 保存当前handle
print(browser.window_handles,browser.current_window_handle)
while True:
    print(browser.window_handles)
    browser.switch_to.window(browser.window_handles[0])
    browser.refresh()
    time.sleep(2)
    study = WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="con_a_1"]/ul/li[1]/div[2]/a')))
    print(study.text)
    if study.text == '继续学习' or study.text == '开始学习':
        study.click()
        browser.switch_to.window(browser.window_handles[-1])
        all_courses=browser.find_elements(By.XPATH,'//*[@id="firstpane"]/div/dl')
        print("所有课程:",[j.text for j in all_courses])
        print(browser.window_handles,browser.current_window_handle)
        for j in range(len(all_courses)):
            browser.switch_to.window(browser.window_handles[-1])
            all_courses=browser.find_elements(By.XPATH,'//*[@id="firstpane"]/div/dl')
            course = all_courses[j]
            print(f"开始学习 {course.text}")
            course.click()
            videoTime = int(eval(browser.find_element(By.XPATH,'//*[@id="videoTime"]').get_attribute("value")))
            alreadyTime = int(eval(browser.find_element(By.XPATH,'//*[@id="alreadyTime"]').get_attribute("value")))
            remainder = videoTime-alreadyTime
            print("视频总长度：",videoTime//3600," 小时 ",(videoTime%3600)//60," 分钟 ",videoTime%60," 秒。")
            print("已学习时间：",alreadyTime//3600," 小时 ",(alreadyTime%3600)//60," 分钟 ",alreadyTime%60," 秒。")
            print(browser.window_handles,browser.current_window_handle)
            if remainder <= 0:
                print("该课程已学完")
                j=j+1
                continue
            else:
                print("课程剩余时间：",remainder//3600," 小时 ",(remainder%3600)//60," 分钟 ",remainder%60," 秒。")
                time.sleep(remainder + 5)
                browser.execute_script("top.$.jBox.close(true)")
                j=j+1
        browser.close()
        time.sleep(2)
        print(browser.window_handles)
    else:
        print("公需科目已学完！")
        break


## 点击专业科目
browser.switch_to.window(browser.window_handles[0])
elem=WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="one2"]')))
elem.click()
print("专业科目")
print(browser.window_handles,browser.current_window_handle)
while True:
    print(browser.window_handles)
    browser.switch_to.window(browser.window_handles[0])
    browser.refresh()
    time.sleep(2)
    study = WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="con_b_1"]/ul/li[1]/div[2]/a',)))
    print(study.text)
    if study.text == '继续学习' or study.text == '开始学习':
        study.click()
        browser.switch_to.window(browser.window_handles[-1])
        all_courses=browser.find_elements(By.XPATH,'//*[@id="firstpane"]/div/dl')
        print("所有课程:",[j.text for j in all_courses])
        print(browser.window_handles,browser.current_window_handle)
        for j in range(len(all_courses)):
            browser.switch_to.window(browser.window_handles[-1])
            all_courses=browser.find_elements(By.XPATH,'//*[@id="firstpane"]/div/dl')
            course = all_courses[j]
            print(f"开始学习 {course.text}")
            course.click()
            try:
                locator = (By.XPATH,'//*[@id="video"]/div[7]/div[3]/div[1]/span[3]' )
                WebDriverWait(browser, 10).until(EC.presence_of_element_located(locator))
                span_element = browser.find_element(*locator)
                time_text = span_element.text
                videoTime = int(time_to_seconds(time_text))
                locator = (By.XPATH,'//*[@id="video"]/div[7]/div[3]/div[1]/span[1]' )
                WebDriverWait(browser, 10).until(EC.presence_of_element_located(locator))
                span_element = browser.find_element(*locator)
                time_text = span_element.text
                alreadyTime = int(time_to_seconds(time_text))
            except:
                videoTime = int(eval(browser.find_element(By.XPATH,'//*[@id="videoTime"]').get_attribute("value")))
                alreadyTime = int(eval(browser.find_element(By.XPATH,'//*[@id="alreadyTime"]').get_attribute("value")))
            remainder = videoTime-alreadyTime
            print("视频总长度：",videoTime//3600," 小时 ",(videoTime%3600)//60," 分钟 ",videoTime%60," 秒。")
            print("已学习时间：",alreadyTime//3600," 小时 ",(alreadyTime%3600)//60," 分钟 ",alreadyTime%60," 秒。")
            print(browser.window_handles,browser.current_window_handle)
            if remainder <= 0:
                print("该课程已学完")
                j=j+1
                continue
            else:
                print("课程剩余时间：",remainder//3600," 小时 ",(remainder%3600)//60," 分钟 ",remainder%60," 秒。")
                time.sleep(remainder + 5)
                browser.execute_script("top.$.jBox.close(true)")
                j=j+1
        browser.close()
        time.sleep(2)
        print(browser.window_handles)
    else:
        print("专业科目已学完！")
        break